import { Injectable } from '@nestjs/common';
import { CreateMenuDto,UpdateMenuDto} from './dto';
import { Repository,In, Not, ReturnDocument } from 'typeorm';
import { InjectRepository} from '@nestjs/typeorm';
import {Menu} from './entities/menu.entity';
import { v4 as uuidv4 } from 'uuid';
import {ResultData} from '../../../common/utils/result';

function buildTreeIterative(data) {
  const idMap = new Map();
  const tree = [];

  // 先创建 Map 映射
  data.forEach(item => {
    idMap.set(item.menuid, { ...item, children: [] });
  });

  // 构造树
  data.forEach(item => {
    const node = idMap.get(item.menuid);
    if (item.parentid == "0" || item.parentid == '') {
      tree.push(node); // 根节点直接放到树中
    } else {
      const parent = idMap.get(item.parentid);
      if (parent) {
        parent.children.push(node); // 添加到父节点的 children
      }
    }
  });

  return tree;
}

@Injectable()
export class MenuService {

  constructor(
    @InjectRepository(Menu)
    private menuRepository: Repository<Menu>,
  ) {}


  async create(menu: CreateMenuDto) {
    menu.create_time = new Date().toLocaleString();
    menu.menuid = uuidv4();
    menu.status = '1';
    const res = await this.menuRepository.insert(menu)
    return ResultData.ok(res);
  }

  async findPage(query,req) {
    const entity = this.menuRepository.createQueryBuilder('sys_menu');
    if (query.pageSize && query.pageNum) {
      entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    }
    const [list, total] = await entity.getManyAndCount();
    const data =  {
      total:total,
      data:list,
    }
    return ResultData.ok(data);
  }

  async find(){
    const res = await this.menuRepository.find();
    return ResultData.ok(res);
  }

  async findTree(){
    const res = await this.menuRepository.find();
    const _res = res.map(item => JSON.parse(JSON.stringify(item)));
    console.log(_res,'_res');
    const data = buildTreeIterative(_res);
    console.log(data);
    return ResultData.ok(data);
  }

  async findOne(menuid: string) {
    const data =  await this.menuRepository.findOne({
        where:{
          menuid:menuid
        }
    })
    return ResultData.ok(data);
  }

  async update(menu: UpdateMenuDto) {
    menu.update_time = new Date().toLocaleString();
    const res = await this.menuRepository.update({ menuid: menu.menuid }, menu) 
    return ResultData.ok(res);
  }

  async remove(ids:string[]) {
    
  }
}
